'use client'

import { useState, useEffect, useCallback } from 'react'
import { Sheet, Cell, CellStyle } from '@/types/sheet'
import { UnifiedSpreadsheetEditor } from '@/components/sheet/UnifiedSpreadsheetEditor'
import { ShareModal } from '@/components/sheet/ShareModal'
import { ImportExportToolbar } from '@/components/sheet/ImportExportToolbar'
import { useYjsCollaboration } from '@/hooks/useYjsCollaboration'
import { useApiCache } from '@/hooks/useApiCache'
import { useAuth } from '@/contexts/AuthContext'
import { ArrowLeft, Users, Wifi, WifiOff, Share2 } from 'lucide-react'
import { cn } from '@/lib/utils'

interface SheetPageProps {
  sheetId: string
  onBack: () => void
}

export const SheetPage: React.FC<SheetPageProps> = ({ sheetId, onBack }) => {
  const { user } = useAuth()
  const { fetchWithCache, debouncedFetch, clearCache } = useApiCache()
  const [sheet, setSheet] = useState<Sheet | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showShareModal, setShowShareModal] = useState(false)
  const [saving, setSaving] = useState(false)
  const [saveSuccess, setSaveSuccess] = useState(false)
  const [cells, setCells] = useState<Cell[]>([])

  // 获取表格详情 - 使用缓存
  const fetchSheet = useCallback(async () => {
    if (!sheetId || !user) return
    
    try {
      setLoading(true)
      
      const sheetData = await fetchWithCache(
        `sheet-${sheetId}`,
        async () => {
          const token = localStorage.getItem('auth_token')
          const response = await fetch(`/api/sheets/${sheetId}`, {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            }
          })
          
          if (!response.ok) {
            const errorData = await response.json()
            throw new Error(errorData.message || 'Failed to fetch sheet')
          }
          
          const data = await response.json()
          
          if (data.success) {
            return data.data
          } else {
            throw new Error(data.message || 'Failed to fetch sheet')
          }
        }
      )
      
      setSheet(sheetData)
      // 获取表格后，立即获取cells数据
      await fetchCells(sheetData)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error')
    } finally {
      setLoading(false)
    }
  }, [sheetId, user, fetchWithCache])

  // 获取表格的cells数据 - 使用缓存和防抖
  const fetchCells = useCallback(async (sheetData: Sheet) => {
    if (!sheetData) return
    
    try {
      const cellsData = await debouncedFetch(
        `cells-${sheetData.id}`,
        async () => {
          const token = localStorage.getItem('auth_token')
          const response = await fetch(`/api/sheets/${sheetData.id}/cells`, {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            }
          })
          
          if (!response.ok) {
            console.warn('Failed to fetch cells:', response.statusText)
            return { cells: [] }
          }
          
          const data = await response.json()
          console.log('Fetched cells:', data.cells)
          return data
        },
        300 // 300ms防抖
      )
      
      // 设置cells数据
      if (cellsData.cells && cellsData.cells.length > 0) {
        setCells(cellsData.cells)
        console.log('Cells data loaded:', cellsData.cells.length, 'cells')
      }
    } catch (err) {
      console.error('Error fetching cells:', err)
    }
  }, [debouncedFetch])

  // 保存单元格数据 - 优化版本
  const handleSaveCells = useCallback(async (cells: Cell[]) => {
    if (!sheet) return

    try {
      setSaving(true)
      const token = localStorage.getItem('auth_token')
      const response = await fetch(`/api/sheets/${sheet.id}/cells/batch`, {
        method: 'PUT',
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ cells })
      })

      if (!response.ok) {
        const errorData = await response.json()
        console.error('API Error:', errorData)
        throw new Error(`Failed to save cells: ${errorData.error || 'Unknown error'}`)
      }
      
      // 保存成功后清理相关缓存
      clearCache(`cells-${sheet.id}`)
      
      setSaveSuccess(true)
      setTimeout(() => setSaveSuccess(false), 2000)
    } catch (err) {
      console.error('Error saving cells:', err)
    } finally {
      setSaving(false)
    }
  }, [sheet, clearCache])

  // 处理单元格更新
  const handleCellUpdate = (row: number, column: number, value: string, formula?: string) => {
    console.log('Cell updated:', { row, column, value, formula })
  }

  // 处理样式更新
  const handleStyleUpdate = (row: number, column: number, style: CellStyle) => {
    console.log('Style updated:', { row, column, style })
  }

  // 处理保存
  const handleSave = async (cellsToSave: Cell[]) => {
    await handleSaveCells(cellsToSave)
  }

  // 处理导入
  const handleImport = async (importedCells: Cell[]) => {
    if (!sheet) return
    
    try {
      setSaving(true)
      const token = localStorage.getItem('auth_token')
      const response = await fetch(`/api/sheets/${sheet.id}/cells/batch`, {
        method: 'PUT',
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ cells: importedCells })
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(`Failed to import cells: ${errorData.error || 'Unknown error'}`)
      }
      
      // 更新本地cells状态
      setCells(importedCells)
      setSaveSuccess(true)
      setTimeout(() => setSaveSuccess(false), 2000)
      
      console.log('文件导入成功，共导入', importedCells.length, '个单元格')
    } catch (err) {
      console.error('Error importing cells:', err)
      alert('文件导入失败')
    } finally {
      setSaving(false)
    }
  }

  // 处理导出
  const handleExport = (format: 'csv' | 'excel') => {
    console.log(`导出为${format}格式`)
  }

  useEffect(() => {
    if (user && sheetId) {
      fetchSheet()
    }
  }, [user, sheetId])

  if (loading) {
    return null
  }

  if (error) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-gray-900 mb-4">加载失败</h1>
          <p className="text-gray-600 mb-4">{error}</p>
          <button
            onClick={onBack}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            返回首页
          </button>
        </div>
      </div>
    )
  }

  if (!sheet) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-gray-900 mb-4">表格不存在</h1>
          <p className="text-gray-600 mb-4">您要访问的表格不存在或已被删除</p>
          <button
            onClick={onBack}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            返回首页
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="flex-1 flex flex-col">
      {/* 顶部工具栏 */}
      <div className="bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 px-4 py-3">
        <div className="flex flex-col space-y-3">
          {/* 第一行：导航和标题 */}
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <button
                onClick={onBack}
                className="flex items-center space-x-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
              >
                <ArrowLeft className="w-5 h-5" />
                <span>返回</span>
              </button>
              <div className="h-6 w-px bg-gray-300 dark:bg-gray-600" />
              <h1 className="text-xl font-semibold text-gray-900 dark:text-white">{sheet.title}</h1>
              {sheet.description && (
                <p className="text-gray-600 dark:text-gray-400">{sheet.description}</p>
              )}
            </div>
          </div>

          {/* 第二行：操作按钮和保存状态 */}
          <div className="flex items-center space-x-6">

            {/* 操作按钮 */}
            <div className="flex items-center space-x-2">
              {/* 导入导出工具栏 */}
              <ImportExportToolbar
                sheet={sheet}
                cells={cells}
                onImport={handleImport}
                onExport={handleExport}
                onSave={handleSave}
              />
              
              <button
                onClick={() => setShowShareModal(true)}
                className="flex items-center space-x-1 px-3 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg"
              >
                <Share2 className="w-4 h-4" />
                <span>分享</span>
              </button>
            </div>

            {/* 保存状态 */}
            <div className="flex items-center space-x-2">
              {saving && (
                <div className="flex items-center space-x-1 text-blue-600 dark:text-blue-400">
                  <div className="w-4 h-4 border-2 border-blue-600 dark:border-blue-400 border-t-transparent rounded-full animate-spin" />
                  <span className="text-sm">保存中...</span>
                </div>
              )}
              {saveSuccess && (
                <div className="flex items-center space-x-1 text-green-600 dark:text-green-400">
                  <span className="text-sm">已保存</span>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 表格内容 */}
      <div className="flex-1">
        <UnifiedSpreadsheetEditor
          sheet={sheet}
          cells={cells}
          onCellUpdate={handleCellUpdate}
          onStyleUpdate={handleStyleUpdate}
          onSave={handleSave}
          containerId="univer-container"
          showCollaboration={true}
          allowEdit={true}
        />
      </div>

      {/* 模态框 */}
      {showShareModal && (
        <ShareModal
          sheet={sheet}
          onClose={() => setShowShareModal(false)}
          onUpdate={(updatedSheet) => setSheet(updatedSheet)}
        />
      )}
    </div>
  )
}
